#!/usr/bin/env bash

function _make_complete_func () {
  local PARAM0 cur opts cmd
  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  now="${COMP_LINE##* }"
  cmd="${COMP_WORDS[COMP_CWORD-1]}"

  PARAM_MAKE="$(make -qp 2>/dev/null | grep -E '^[a-zA-Z0-9_-]+:([^=]|$$)' | sed 's/://' | grep -Ev 'Makefile|makefile|GNUmakefile|:=')"
  PARAM_ENV="$(grep -oE '^[A-Z_][A-Z0-9_]*[[:space:]]*[:]?=' Makefile 2>/dev/null | grep -oE '[A-Z_][A-Z0-9_]*' | sed 's/$/=/')"
  case "${cmd}" in
  make)
    opts="$PARAM_MAKE"
    COMPREPLY=($(compgen -W "$opts" -- "$cur"))
    ;;
  *)
    opts="$PARAM_ENV"
    COMPREPLY=($(compgen -o default -W "$opts" -- "$cur"))
    ;;
  esac
}
complete -o nospace -F _make_complete_func make
